package com.sensorfriendly.ui;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.sensorfriendly.AppConstants;
import com.sensorfriendly.AppContext;
import com.sensorfriendly.R;
import com.sensorfriendly.model.Scenario;
import com.sensorfriendly.util.ImageUtil;

/**
 * 
 * Adpater for hosting list of scenaiors
 */
public class ScenarioListAdapter extends BaseAdapter {

	private Activity activity;
	List<Scenario> data;
	private static LayoutInflater inflater = null;

	public ScenarioListAdapter(Activity a, List<Scenario> d) {
		activity = a;
		data = d;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public int getCount() {
		return data.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("ShowToast")
	public View getView(final int position, View convertView, ViewGroup parent) {
		View vi = convertView;
		if (convertView == null)
			vi = inflater.inflate(R.layout.list_row, null);

		TextView scenarioTitle = (TextView) vi
				.findViewById(R.id.list_item_title);
		ImageView icon = (ImageView) vi.findViewById(R.id.scenario_icon);
		final Scenario scenario = data.get(position);

		// Setting all values in listview
		scenarioTitle.setText(scenario.toString());
		
		
		
		if (scenario.getIconPath() != null) {
			// set the customized icon if available
			InputStream is = null;
			try {
				is = activity.getAssets().open(scenario.getIconPath());
			} catch (IOException e) {
				// TODO SENSOR handle image loading failed
				e.printStackTrace();
			}
			if (is != null) {
				final BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(is, null, options);
				int reqWidth = 50;
				int reqHeight = 50;
				options.inSampleSize = ImageUtil.calculateInSampleSize(options,
						reqWidth, reqHeight);
				// Decode bitmap with inSampleSize set
				options.inJustDecodeBounds = false;
				Bitmap image = BitmapFactory.decodeStream(is, null, options);
				icon.setImageBitmap(image);
			}
		}else{
			//use default icon if its not.
			icon.setImageResource(R.drawable.windows);
		}

		/****************************************
		 * Handling for the Delete Button
		 ****************************************/
		Button delete_button = (Button) vi.findViewById(R.id.delete_button);
		delete_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// Alert Dialog to confirm if the scenario should
				// be deleted or not
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						activity);

				// set title
				alertDialogBuilder.setTitle("ALERT : Delete Scenario?");

				alertDialogBuilder
						.setMessage("Are you sure you want to delete the scenario : "
								+ scenario.toString());
				alertDialogBuilder.setCancelable(false);

				alertDialogBuilder.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// Delete the Scenario
								final AppContext app = (AppContext) activity
										.getApplication();
								app.deleteScenario(scenario.toString()
										.toLowerCase());

								// Update the list in case of a change
								ScenarioListAdapter.this.data = app.getAllScenarios();
								ScenarioListAdapter.this.notifyDataSetChanged();
							}
						});

				alertDialogBuilder.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								dialog.cancel();
							}
						});

				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();

				// show it
				alertDialog.show();
			}
		});

		/****************************************
		 * Handling for the Edit Button
		 ****************************************/
		Button edit_button = (Button) vi.findViewById(R.id.edit_button);
		edit_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// AlertDialog.Builder alertDialogBuilder = new
				// AlertDialog.Builder(activity);
				//
				// alertDialogBuilder.setTitle("Edit Scenario Name");
				// //alertDialogBuilder.setMessage("Please enter the Scenario Name");
				//
				// // Set an EditText view to get user input
				// final EditText newScenarioName = new EditText(activity);
				// newScenarioName.setSingleLine();
				// newScenarioName.setText(scenario.toString());
				// alertDialogBuilder.setView(newScenarioName);
				//
				// alertDialogBuilder.setPositiveButton("Ok", new
				// DialogInterface.OnClickListener() {
				// public void onClick(DialogInterface dialog, int whichButton)
				// {
				// String value = newScenarioName.getText().toString();
				//
				// // Edit the Scenario Name if the current name
				// // has been changed and is not empty
				// if(!scenario.toString().equalsIgnoreCase(value)
				// &&
				// !value.trim().matches("")){
				// final AppContext app = (AppContext)
				// activity.getApplication();
				// app.editScenarioName(scenario.toString().toLowerCase(),
				// value);
				//
				// // Update the list in case of a change
				// ScenarioListAdapter.this.notifyDataSetChanged();
				// }
				// }
				// });
				//
				// alertDialogBuilder.setNegativeButton("Cancel", new
				// DialogInterface.OnClickListener() {
				// public void onClick(DialogInterface dialog, int whichButton)
				// {
				// // Canceled.
				// }
				// });
				//
				// alertDialogBuilder.show();
				
				//always show the complete scenario editing dialog
				Intent intent = new Intent(activity, EditScenarioDialog.class);
				intent.putExtra(AppConstants.CATEGORY, data.get(position)
						.getName());
				activity.startActivity(intent);
			}
		});

		return vi;
	}
	
	public void setScenarios(List<Scenario> scenarios){
		this.data = scenarios;
	}
}